package com.shu.auth.service.impl;

import com.google.common.base.Preconditions;
import com.shu.auth.dao.SysDeptMapper;
import com.shu.auth.exception.CodeMsg;
import com.shu.auth.exception.ParamException;
import com.shu.auth.model.SysDept;
import com.shu.auth.service.IDeptService;
import com.shu.auth.utils.BeanValidator;
import com.shu.auth.utils.LevelUtil;
import com.shu.auth.vo.DeptVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service("deptService")
public class DeptServiceImpl implements IDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;


    @Override
    public void save(DeptVo deptVo) {
        //校验入参
        BeanValidator.check(deptVo);
        //判断是否已经存在部门
        if (checkExist(deptVo.getParentId(),deptVo.getName(),deptVo.getId())){
            throw new ParamException(CodeMsg.D00001.getCodeMsg());
        }
        SysDept dept=SysDept.builder().name(deptVo.getName()).parentId(deptVo.getParentId())
                .seq(deptVo.getSeq()).remark(deptVo.getRemark()).build();

        //得到上一个部门的level，并
        dept.setLevel(LevelUtil.calculateLevel(getLevel(dept.getParentId()),dept.getParentId()));
        dept.setOperator("system-save");//TODO:
        dept.setOperateTime(new Date());
        dept.setOperateIp("127.0.0.1");//TODO:
        sysDeptMapper.insertSelective(dept);

    }
    @Override
    public void update(DeptVo deptVo){
        //校验入参
        BeanValidator.check(deptVo);
        //判断是否已经存在部门
        if (checkExist(deptVo.getParentId(),deptVo.getName(),deptVo.getId())){
            throw new ParamException(CodeMsg.D00001.getCodeMsg());
        }
        SysDept before = sysDeptMapper.selectByPrimaryKey(deptVo.getId());
        //判断之前的部门是否存在
        Preconditions.checkNotNull(before,"待更新的部门不存在");
        //new一个部门
        SysDept after=SysDept.builder().id(deptVo.getId()).name(deptVo.getName()).parentId(deptVo.getParentId())
                .seq(deptVo.getSeq()).remark(deptVo.getRemark()).build();

        after.setLevel(LevelUtil.calculateLevel(getLevel(deptVo.getId()),deptVo.getParentId()));
        after.setOperator("system-update");//TODO:
        after.setOperateTime(new Date());
        after.setOperateIp("127.0.0.1");//TODO:
        //更新子部门
        updateWithChild(before,after);
    }
    @Transactional
    void updateWithChild(SysDept before, SysDept after){


        String newLevelPrefix=after.getLevel();
        String oldLevelProfix=before.getLevel();

        if (!newLevelPrefix.equals(oldLevelProfix)){
            List<SysDept> childDeptList= sysDeptMapper.getChildDeptListByLevel(oldLevelProfix);
            if (CollectionUtils.isNotEmpty(childDeptList)){
                for (SysDept sysDept:childDeptList){
                    String level=sysDept.getLevel();
                    if (level.indexOf(oldLevelProfix)==0){
                        level=newLevelPrefix+level.substring(oldLevelProfix.length());
                        sysDept.setLevel(level);
                    }
                }
                sysDeptMapper.batchUpdateLevel(childDeptList);
            }
        }
        sysDeptMapper.updateByPrimaryKey(after);
    }
    private boolean checkExist(Integer parentId,String deptName,Integer deptId){
        //如果数据库中部门大于0代表存在
        return sysDeptMapper.countByNameAndParentId(parentId,deptName,deptId)>0;
    }

    /**
     * 获得部门的等级
     * @param deptId
     * @return
     */
    private String getLevel(Integer deptId){
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(deptId);
        if (sysDept==null){
            return null;
        }
        return sysDept.getLevel();
    }
}
